<script setup>
import {onMounted, ref} from 'vue';
import {Lock, User} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";
import {useTokenStore} from "@/stores/token.js";
import {userLoginService, userRegisterService} from "@/api/admin/user.js";
import {ElMessage} from "element-plus";
import { schoolListService } from '@/api/admin/school.js'

let signUpButton = null;
let signInButton = null;
let container = null;
const schools = ref([]);
let registerData = ref({
  username: '',
  password: '',
  rePassword: '',
  schoolId: ''
})

// 定义选中的学校
const selectedSchool = ref({});
// 处理命令事件，更新选中的学校
const handleCommand = (command) => {
  selectedSchool.value = command;
  registerData.value.schoolId = command.id;
};
const initSchools = async () => {
  const result = await schoolListService();
  schools.value = result.data;
};

onMounted(() => {
  initSchools();
  signUpButton = document.getElementById('signUp');
  signInButton = document.getElementById('signIn');
  container = document.getElementById('dowebok');

  signUpButton.addEventListener('click', function () {
    container.classList.add('right-panel-active');
  });

  signInButton.addEventListener('click', function () {
    container.classList.remove('right-panel-active');
  });
});

const router = useRouter()
const tokenStore = useTokenStore()

// 校验密码的函数
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerData.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
// 定义表单校验规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  // password: [
  //   { required: true, message: '请输入密码', trigger: 'blur' },
  //   { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  // ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z]).*$/,
      message: '密码必须包含大写字母和小写字母',
      trigger: 'blur'
    },
    {
      pattern: /^(?=.*[\d\W_]).*$/,
      message: '密码必须包含数字或特殊符号',
      trigger: 'blur'
    },
    {
      pattern: /^.{8,}$/,
      message: '密码长度必须大于等于8位',
      trigger: 'blur'
    }
  ],
  rePassword: [
    { validator: checkRePassword, trigger: 'blur' }
  ]
})
// 定义了一个异步函数 register，用于用户注册
const register = async () => {
  const result = await userRegisterService(registerData.value);
  registerData.value = {
    username: '',
    password: '',
    rePassword: '',
    schoolId: ''
  };
  selectedSchool.value = {};
  if (result.message === '操作成功') {
    ElMessage.success('注册成功')
  } else {
    ElMessage.error(result.message)
  }
}
// 登录函数
const login = async () => {
  const result = await userLoginService(registerData.value)
  console.log(result)
  if (result.data !== null) {
    ElMessage.success('欢迎登录！')
    await router.push('/layout')
    tokenStore.setToken(result.data)
  } else {
    ElMessage.error(result.message)
  }
}
</script>

<template>
  <div class="content">
    <div class="dowebok" id="dowebok">
      <div class="form-container sign-up-container">
        <form id="signup-form">
          <el-form ref="form" size="large" autocomplete="off" :model="registerData" :rules="rules">
            <el-form-item >
              <div style="margin: 0 auto">
                <h1 style="">注册</h1>
              </div>
<!--              <div class="social-container">-->
<!--                <a href="#" class="social"><img style="width: 20px;" src='../assets/images/qq.png' alt=""></a>-->
<!--                <a href="#" class="social"><img style="width: 20px;" src='../assets/images/wx.png' alt=""></a>-->
<!--                <a href="#" class="social"><img style="width: 20px;" src='../assets/images/github.png' alt=""></a>-->
<!--              </div>-->
            </el-form-item>
            <el-form-item prop="schoolId">
              <el-dropdown split-button trigger="click" @command="handleCommand">
    <span class="el-dropdown-link">
      {{ selectedSchool.name || '请选择学校' }}
    </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                        v-for="(school, index) in schools"
                        :key="index"
                        :command="school"
                    >
                      <img :src="school.schoolBadge" alt="" class="school-icon" />
                      {{ school.name }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-form-item>
            <el-form-item prop="username">
              <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
            </el-form-item>
            <el-form-item prop="rePassword">
              <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button class="button" type="primary" auto-insert-space @click="register">
                注册
              </el-button>
            </el-form-item>
          </el-form >
        </form>
      </div>


      <div class="form-container sign-in-container">
        <form id="signin-form">
          <el-form ref="form" size="large" autocomplete="off" v-if="!isRegister" :model="registerData" :rules="rules">
            <el-form-item>
              <div style="margin: 0 auto">
                <h1 style="">登录</h1>
              </div>
<!--              <div class="social-container">-->
<!--                <a href="#" class="social"><img style="width: 20px;" src='../assets/images/qq.png' alt=""></a>-->
<!--                <a href="#" class="social"><img style="width: 20px;" src='../assets/images/wx.png' alt=""></a>-->
<!--                <a href="#" class="social"><img style="width: 20px;" src='../assets/images/github.png' alt=""></a>-->
<!--              </div>-->
            </el-form-item>
            <el-form-item prop="username">
              <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
            </el-form-item>
            <!-- 登录按钮 -->
            <el-form-item>
              <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
            </el-form-item>
          </el-form>
        </form>
      </div>
      <div class="overlay-container">
        <div class="overlay">
          <div class="overlay-panel overlay-left">
            <h1>已有帐号？</h1>
            <p>请使用您的帐号进行登录</p>
            <button class="ghost" id="signIn">登录</button>
          </div>
          <div class="overlay-panel overlay-right">
            <h1>没有帐号？</h1>
            <p>立即注册加入我们，和我们一起开始旅程吧</p>
            <button class="ghost" id="signUp">注册</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
* {
  box-sizing: border-box;
}

.content{
  background-image: url("../assets/images/backgroundphoto.webp");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
}

h1 {
  font-weight: bold;
  margin: 0;
}

p {
  font-size: 14px;
  line-height: 20px;
  letter-spacing: .5px;
  margin: 20px 0 30px;
}

span {
  font-size: 12px;
}

a {
  color: #333;
  font-size: 14px;
  text-decoration: none;
  margin: 15px 0;
}

.dowebok {
  border-radius: 10px;
  box-shadow: 0 14px 28px rgba(0, 0, 0, .25), 0 10px 10px rgba(0, 0, 0, .22);
  position: relative;
  overflow: hidden;
  width: 55vw;
  height: 70vh;
  max-width: 100%;
  margin: 12vh auto;
  opacity: 0.85;
}

.form-container form {
  background: #fff;
  display: flex;
  flex-direction: column;
  padding: 0 50px;
  height: 100%;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.social-container {
  margin: 20px auto;
}

.social-container a {
  border: 1px solid #ddd;
  border-radius: 50%;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin: 0 5px;
  height: 40px;
  width: 40px;
}

.social-container a:hover {
  background-color: #eee;
}

.form-container input {
  background: #eee;
  border: none;
  padding: 12px 15px;
  margin: 8px 0;
  width: 100%;
  border-radius: 10px;
  outline: none;
}

button {
  border-radius: 20px;
  border: 1px solid #ffffff;
  background: #2bbcff;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
  padding: 12px 45px;
  letter-spacing: 1px;
  text-transform: uppercase;
  transition: transform 80ms ease-in;
  cursor: pointer;
}

button:active {
  transform: scale(.95);
}

button:focus {
  outline: none;
}

button.ghost {
  background: transparent;
  border-color: #fff;
}

.form-container {
  position: absolute;
  top: 0;
  height: 100%;
  transition: all .6s ease-in-out;
}

.sign-in-container {
  left: 0;
  width: 50%;
  z-index: 2;
}

.sign-up-container {
  left: 0;
  width: 50%;
  z-index: 1;
  opacity: 0;
}

.overlay-container {
  position: absolute;
  top: 0;
  left: 50%;
  width: 50%;
  height: 100%;
  overflow: hidden;
  transition: transform .6s ease-in-out;
  z-index: 100;
}

.overlay {
  background: #41b6ff;
  background: linear-gradient(to top, #ffffff, #00aeff) no-repeat 0 0 / cover;
  color: #ffffff;
  position: relative;
  left: -100%;
  height: 100%;
  width: 200%;
  transform: translateY(0);
  transition: transform .6s ease-in-out;
}

.overlay-panel {
  position: absolute;
  top: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0 40px;
  height: 100%;
  width: 50%;
  text-align: center;
  transform: translateY(0);
  transition: transform .6s ease-in-out;
}

.overlay-right {
  right: 0;
  transform: translateY(0);
}

.overlay-left {
  transform: translateY(-20%);
}

/* Move signin to right */
.dowebok.right-panel-active .sign-in-container {
  transform: translateY(100%);
}

/* Move overlay to left */
.dowebok.right-panel-active .overlay-container {
  transform: translateX(-100%);
}

/* Bring signup over signin */
.dowebok.right-panel-active .sign-up-container {
  transform: translateX(100%);
  opacity: 1;
  z-index: 5;
}

/* Move overlay back to right */
.dowebok.right-panel-active .overlay {
  transform: translateX(50%);
}

/* Bring back the text to center */
.dowebok.right-panel-active .overlay-left {
  transform: translateY(0);
}

/* Same effect for right */
.dowebok.right-panel-active .overlay-right {
  transform: translateY(20%);
}

.school-icon {
  width: 16px; /* 根据需要调整图片大小 */
  height: 16px;
  margin-right: 8px; /* 图片与文字之间的间距 */
}
</style>
